/* eslint-disable indent */
// 路由实例
import router, { asyncRoutes } from './router'
// vuex
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
    // start progress bar
    NProgress.start()
    if (store.getters.token) {
        // 存在token
        if (to.path === '/login') {
            // 如果再次访问登录页=》回到首页
            next('/')
        } else {
            next() // 访问页面
                // 判断当前登录人信息有没有获取过
            if (!store.getters.name) {
                const perms = await store.dispatch('user/getUserInfo')
                const canLook = asyncRoutes.filter(route => {
                        // menus中如果包含当前route的name=》留下
                        return perms.menus.includes(route.children[0].name)
                    })
                    // 存储菜单数据
                store.commit('menus/setMenuList', canLook)
                console.log('当前登录人权限点数据：', perms, canLook)
                    // 动态添加路由配置
                router.addRoutes([...canLook, { path: '*', redirect: '/404', hidden: true }])
            }
        }
    } else {
        //  不存在token=>可能访问的是登录页
        if (whiteList.includes(to.path)) {
            next()
        } else {
            // 携带当前要访问的页面路径
            next(`/login?redirect=${to.path}`)
        }
    }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
        // eslint-disable-next-line eol-last
})